const { Model, DataTypes } = require('sequelize');
const sequelize = require('../db/db');
const QuestionSet = require('./QuestionSet');
const Question = require('./Question');

class QuestionSetItem extends Model {}

QuestionSetItem.init(
  {
    id: {
      type: DataTypes.CHAR(18),
      primaryKey: true,
      allowNull: false,
      comment: '关联记录ID'
    },
    set_id: {
      type: DataTypes.CHAR(18),
      allowNull: false,
      comment: '题库ID',
      references: {
        model: QuestionSet,
        key: 'id'
      }
    },
    question_id: {
      type: DataTypes.CHAR(18),
      allowNull: false,
      comment: '题目ID',
      references: {
        model: Question,
        key: 'id'
      }
    },
    order_num: {
      type: DataTypes.INTEGER,
      defaultValue: 0,
      comment: '排序号'
    },
    create_time: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW,
      comment: '添加时间'
    }
  },
  {
    sequelize,
    modelName: 'QuestionSetItem',
    tableName: 'question_set_item',
    timestamps: false,
    indexes: [
      {
        fields: ['set_id']
      },
      {
        fields: ['question_id']
      },
      {
        unique: true,
        fields: ['set_id', 'question_id']
      }
    ]
  }
);

// 建立与QuestionSet的关联关系
QuestionSetItem.belongsTo(QuestionSet, {
  foreignKey: 'set_id',
  targetKey: 'id',
  as: 'questionSet'
});

// 建立与Question的关联关系
QuestionSetItem.belongsTo(Question, {
  foreignKey: 'question_id',
  targetKey: 'id',
  as: 'question'
});

// 在QuestionSet和Question模型中添加关联关系
setTimeout(() => {
  // 设置QuestionSet与Question的多对多关联
  QuestionSet.belongsToMany(Question, {
    through: QuestionSetItem,
    foreignKey: 'set_id',
    otherKey: 'question_id',
    as: 'questions'
  });

  Question.belongsToMany(QuestionSet, {
    through: QuestionSetItem,
    foreignKey: 'question_id',
    otherKey: 'set_id',
    as: 'questionSets'
  });
}, 0);

module.exports = QuestionSetItem; 